//
//  TEA_CustomView.swift
//  ChallengeProject
//
//  Created by mac on 2023/9/7.
//  Copyright © 2023 XX. All rights reserved.
//

import UIKit
import PGDatePicker
import Kingfisher

class Card_ListCell: UITableViewCell {
    
    let img = UIImageView.initImgView(img: "")
    let nameLabel = UILabel.initV(.setTypeFace(18,type: .bold), text: "", textColor: mainColor)
    let backV = UIView.init(frame: .zero)
    var nameString = ""{
        didSet{
            nameLabel.text = nameString
            img.image = .init(named: nameString)
        }
    }
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.subviews {
            backV.subviews {
                img
                nameLabel
            }
        }
        backV.backgroundColor = .white
        backV.left(0).top(0).right(0).bottom(10.Fit)
        backV.setAllCorners(corner: 10.Fit)
        
        img.size(50.Fit).left(20.Fit).top(10.Fit)
        nameLabel.height(40.Fit).right(20.Fit).top(15.Fit)
        nameLabel.Leading == img.Trailing + 15.Fit
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
class Card_ListView: UIView {
    
    let arr = ["Dog","Cat","Bird","Rabbit","Fish","Others"]
    var doneBlock:((String,Int) -> Void)?
    
    private lazy var table: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.showsVerticalScrollIndicator = false
        view.register(Card_ListCell.self, forCellReuseIdentifier: "cell")
        view.rowHeight = 80.Fit
        return view
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.subviews {
            table
        }
        table.fillContainer()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension Card_ListView:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Card_ListCell
        cell.selectionStyle = .none
        cell.nameString = arr[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.doneBlock?(arr[indexPath.row],indexPath.row)
        superview?.animatedDismiss()
    }
    
}

class ReportSuccess_View: UIView {
    
    private var imgView = UIImageView.initImgView(img: "report")
    private var tLabel = UILabel.initV(.setTypeFace(18, type: .bold), text: "Tips", textColor: mainColor)
    private var cLabel = UILabel.initV(.setTypeFace(13, type: .medium), text: "You have successfully reported the user", textColor:mainColor)
    private lazy var submitBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("OK", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .setTypeFace(20, type: .bold)
        btn.setAllCorners(corner: 25.Fit)
        btn.backgroundColor = mainColor
        return btn
    }()
    var type = 0{
        didSet{
            cLabel.text = type == 0 ? "You have successfully reported the user" : "You have blocklisted the user"
        }
    }
            
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        layer.cornerRadius = 25.Fit
        layer.maskedCorners = .allCorner
        self.subviews {
            imgView
            tLabel
            cLabel
            submitBtn
        }
        imgView.top(20.Fit).size(120.Fit)
        imgView.centerHorizontally()
        
        tLabel.textAlignment = .center
        tLabel.left(20.Fit).right(20.Fit)
        tLabel.Top == imgView.Bottom + 10.Fit
        
        cLabel.textAlignment = .center
        cLabel.numberOfLines = 0
        cLabel.left(20.Fit).right(20.Fit).height(20.Fit)
        cLabel.Top == tLabel.Bottom + 15.Fit

        submitBtn.left(25).bottom(20.Fit).right(25).height(50.Fit)
        submitBtn.addAct {
            Toast_View_Tool.dismiss()
            self.superview?.animatedDismiss()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


class Block_View: UIView {
    
    private var imgView = UIImageView.initImgView(img: "blockicon")
    private var tLabel = UILabel.initV(.setTypeFace(20, type: .medium), text: "Black", textColor:titleColor)
    private var cLabel = UILabel.initV(.setTypeFace(14, type: .medium), text: "You can’t see the user’s activity after being blacked out.", textColor:.color(hexString: "#999999"))
    private lazy var submitBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Still want to block", for: .normal)
        btn.setTitleColor(mainColor, for: .normal)
        btn.titleLabel?.font = .setTypeFace(16, type: .medium)
        btn.setAllCorners(corner: 25.Fit)
        btn.backgroundColor = .black
        return btn
    }()
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Cancel", for: .normal)
        btn.setTitleColor(.color(hexString: "#999999"), for: .normal)
        btn.titleLabel?.font = .setTypeFace(16, type: .medium)
        btn.backgroundColor = .clear
        return btn
    }()
    var userID:String?

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        layer.cornerRadius = 20.Fit
        layer.maskedCorners = .allCorner
        self.subviews {
            imgView
            tLabel
            cLabel
            submitBtn
            cancelBtn
        }
        imgView.top(15.Fit).left(0).right(0).height(200.Fit)
        imgView.centerHorizontally()
        
        tLabel.textAlignment = .center
        tLabel.left(20.Fit).right(20.Fit)
        tLabel.Top == imgView.Bottom
        
        cLabel.textAlignment = .center
        cLabel.numberOfLines = 0
        cLabel.left(20.Fit).right(20.Fit).height(40.Fit)
        cLabel.Top == tLabel.Bottom + 5.Fit
        
        submitBtn.right(15.Fit).left(15.Fit).height(50.Fit)
        submitBtn.Top == cLabel.Bottom + 10.Fit
        submitBtn.addAct {
            Toast_View_Tool.show()
            self.superview?.animatedDismiss()
            //拉黑
            RT.blockWithUserid(userid:self.userID ?? "", type: "1") { str in
                Toast_View_Tool.show(type:.success,text: "Success")
                if var blockUserIds = UserDefaults.standard.stringArray(forKey: "block_userIds") {
                    blockUserIds.append(self.userID ?? "")
                    UserDefaults.standard.set([blockUserIds], forKey: "block_userIds")
                } else {
                    UserDefaults.standard.set([self.userID ?? ""], forKey: "block_userIds")
                }
                NotificationCenter.default.post(name: NSNotification.Name("BlockRefreshNotice"), object: nil)
            }
        }
        
        cancelBtn.right(15.Fit).left(15).height(50.Fit)
        cancelBtn.Top == submitBtn.Bottom
        cancelBtn.addAct {
            self.superview?.animatedDismiss()
        }

        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

class commentView: UIViewController,UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate {
    
    let backV = UIView.init(frame: .zero)
    var coomentDataSource:[InfoUtil.commentDta] = []

    private lazy var itemsTableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .clear
        view.register(CommentCell.self, forCellReuseIdentifier: CommentCell.description())
        view.rowHeight = UITableView.automaticDimension
        return view
    }()
    let titleL = UILabel.initV(UIFont.setTypeFace(20,type: .medium), text: "Comment", textColor: titleColor)
    let closeB = UIButton.initV(img: "close12")
    let inputV = UIView.init(frame: .zero)
    let txtfiled1 = UITextField.init(frame: .zero)
    var model:InfoUtil.room?{
        didSet{
            coomentDataSource.removeAll()
            if let str = self.model?.info5,str.count != 0 {
                let arr = str.components(separatedBy: "@@")
                for dict in arr{
                    if let d = InfoUtil.commentDta.deserialize(from: dict){
                        coomentDataSource.append(d)
                    }
                }
                self.itemsTableView.reloadData()
            }
        }
    }
    var doneB:(() -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .blackComponent(0.3)
        self.view.subviews {
            backV.subviews {
                titleL
                closeB
                inputV.subviews {
                    txtfiled1
                }
                itemsTableView
            }
        }
        
        backV.isUserInteractionEnabled = true
        backV.backgroundColor = .white
        backV.left(0).right(0).bottom(0).height(495.Fit)
        backV.layer.maskedCorners = [.layerMaxXMinYCorner,.layerMinXMinYCorner]
        backV.layer.cornerRadius = 20.Fit
        
        titleL.left(50.Fit).right(50.Fit).top(25.Fit)
        titleL.centerHorizontally()
        titleL.textAlignment = .center
        
        closeB.size(40.Fit).right(15.Fit).top(25.Fit)
        closeB.addAct {
            self.dismiss(animated: false)
        }
        
        inputV.left(0).right(0).bottom(0).height(50.Fit + TabbarSafeBottomMargin)
        let attriText = NSMutableAttributedString.init(string: "Say Something")
        attriText.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.color(hexString: "#EBC88C",alpha: 1)], range: NSRange(location: 0, length: attriText.string.count))
        txtfiled1.attributedPlaceholder = attriText
        txtfiled1.textColor = .black
        txtfiled1.backgroundColor = .color(hexString: "#FFF1DA")
        txtfiled1.font = .setTypeFace(15.Fit,type: .medium)
        txtfiled1.setAllCorners(corner: 20.Fit)
        txtfiled1.delegate = self
        txtfiled1.leftView = .init(frame: .init(x: 0, y: 0, width: 20.Fit, height: 20))
        txtfiled1.leftViewMode = .always
        txtfiled1.returnKeyType = .send
        txtfiled1.left(15.Fit).right(15.Fit).height(40.Fit).top(15.Fit)

        itemsTableView.left(0).right(0)
        itemsTableView.Top == titleL.Bottom + 15.Fit
        itemsTableView.Bottom == inputV.Top
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        guard self.txtfiled1.text?.isBlank == false else {
            return false
        }
        let date = Date()
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = "MM-dd HH:mm"
        let strNowTime = timeFormatter.string(from: date) as String
        let model:InfoUtil.commentDta? = InfoUtil.commentDta.init(headImg: USEINFOMODEL.headImage,name: USEINFOMODEL.name,content: self.txtfiled1.text,time: strNowTime,id:USEINFOMODEL.id,zan:"")
        var arr:[String] = self.model?.info5?.components(separatedBy: "@@") ?? []
        arr.append(model?.toJSONString() ?? "")
        self.model?.info5 = arr.joined(separator: "@@")
        RT.updateHouse(paraInfo: (self.model?.toJSON())!) { info in
            self.model = info
            self.txtfiled1.resignFirstResponder()
            self.txtfiled1.text = ""
            self.doneB?()
        }
        return true
        
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.coomentDataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CommentCell.description(), for: indexPath) as! CommentCell
        cell.model = self.coomentDataSource[indexPath.row]
        return cell
    }
    
}


class DeleteRoom_View: UIView {
    
    private var imgView = UIImageView.initImgView(img: "picture_delete content")
    private var tLabel = UILabel.initV(.setTypeFace(20, type: .medium), text: "Delete the content?", textColor:titleColor)
    private var cLabel = UILabel.initV(.setTypeFace(14, type: .medium), text: "Once content is deleted it cannot be recovered.", textColor:.color(hexString: "#999999"))
    private lazy var submitBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Yes", for: .normal)
        btn.setTitleColor(mainColor, for: .normal)
        btn.titleLabel?.font = .setTypeFace(16, type: .medium)
        btn.setAllCorners(corner: 25.Fit)
        btn.backgroundColor = .black
        return btn
    }()
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Cancel", for: .normal)
        btn.setTitleColor(.color(hexString: "#999999"), for: .normal)
        btn.titleLabel?.font = .setTypeFace(16, type: .medium)
        btn.backgroundColor = .clear
        return btn
    }()
    var userID:String?
    var deleBlock:(() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        layer.cornerRadius = 20.Fit
        layer.maskedCorners = .allCorner
        self.subviews {
            imgView
            tLabel
            cLabel
            submitBtn
            cancelBtn
        }
        imgView.top(15.Fit).left(0).right(0).height(200.Fit)
        imgView.centerHorizontally()
        
        tLabel.textAlignment = .center
        tLabel.left(20.Fit).right(20.Fit)
        tLabel.Top == imgView.Bottom
        
        cLabel.textAlignment = .center
        cLabel.numberOfLines = 0
        cLabel.left(20.Fit).right(20.Fit).height(40.Fit)
        cLabel.Top == tLabel.Bottom + 5.Fit
        
        submitBtn.right(15.Fit).left(15.Fit).height(50.Fit)
        submitBtn.Top == cLabel.Bottom + 10.Fit

        cancelBtn.right(15.Fit).left(15).height(50.Fit)
        cancelBtn.Top == submitBtn.Bottom
        
        cancelBtn.addAct {
            self.superview?.animatedDismiss()
        }
        submitBtn.addAct {
            self.superview?.animatedDismiss()
            self.deleBlock?()
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

class Record_View: UIView,PGDatePickerDelegate {
    
    private var tLabel = UILabel.initV(.setTypeFace(20, type: .bold), text: "Record", textColor: titleColor)
    let backView = UIView.init(frame: .zero)
    var imgUrl = ""
    private lazy var doneButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = .setTypeFace(16.Fit,type: .medium)
        button.setTitleColor(mainColor, for: .normal)
        button.setTitle("Done", for: .normal)
        button.backgroundColor = .black
        button.layer.cornerRadius = 25
        return button
    }()
    private lazy var cancelButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = .setTypeFace(16.Fit,type: .medium)
        button.setTitleColor(.color(hexString: "#999999"), for: .normal)
        button.setTitle("Cancel", for: .normal)
        button.backgroundColor = .clear
        button.layer.cornerRadius = 25
        return button
    }()
    
    let typeB = UIButton.initV(img: "")
    let typeimg = UIImageView.initImgView(img: "")
    let typeLabel = UILabel.initV(.setTypeFace(15, type: .system), text: "", textColor: titleColor)

    private lazy var descView: Custom_TextView = {
        let view = Custom_TextView()
        view.backgroundColor = UIColor.clear
        view.textContainerInset = UIEdgeInsets(top: 10.Fit, left: 10.Fit, bottom: 10.Fit, right: 10.Fit)
        view.tintColor = titleColor
        view.textColor = titleColor
        view.placeHolderColor = UIColor.color(hexString: "#EBC88C",alpha: 1)
        view.placeHolder = "Write down what you will do…"
        view.returnKeyType = .done
        view.font = .setTypeFace(16.Fit,type: .medium)
        return view
    }()
    let addB = UIButton.initV(img: "")
    var recordBlock:(() -> Void)?
    let iconi = UIImageView.initImgView(img: "icon_xiala")
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        layer.cornerRadius = 25.Fit
        layer.maskedCorners = .allCorner
        self.subviews {
            tLabel
            backView.subviews {
                typeB.subviews {
                    typeimg
                    typeLabel
                }
                descView
            }
            addB.subviews {
                iconi
            }
            doneButton
            cancelButton
        }
        
        tLabel.textAlignment = .center
        tLabel.left(15.Fit).right(15.Fit).top(20.Fit).height(25.Fit)
        
        backView.backgroundColor = mainColor.withAlphaComponent(0.3)
        backView.left(15.Fit).right(15.Fit).height(165.Fit)
        backView.setAllCorners(corner: 10.Fit)
        backView.Top == tLabel.Bottom + 20.Fit
        
        typeB.left(15.Fit).top(15.Fit).height(40.Fit).width(120.Fit)
        typeB.backgroundColor = mainColor
        typeB.setAllCorners(corner: 10.Fit)
        
        typeimg.size(30.Fit).left(5.Fit)
        typeimg.centerVertically()
        
        typeLabel.left(45.Fit).right(5.Fit).height(20.Fit)
        typeLabel.CenterY == typeimg.CenterY
        
        descView.left(15.Fit).right(15.Fit).bottom(15.Fit)
        descView.Top == typeB.Bottom + 10.Fit
        
        addB.left(15.Fit).right(15.Fit).height(40.Fit)
        addB.Top == backView.Bottom + 15.Fit
        addB.backgroundColor = mainColor.withAlphaComponent(0.3)
        addB.setAllCorners(corner: 20.Fit)
        iconi.size(30.Fit).right(10.Fit)
        iconi.centerVertically()
        
        let now = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy/MM/dd"
        let dateString = dateFormatter.string(from: now) // 将 Date 对象转换为字符串
        addB.setTitle(dateString, for: .normal)
        addB.setTitleColor(.blackComponent(0.3), for: .normal)
        addB.contentHorizontalAlignment = .left
        addB.titleEdgeInsets = .init(top: 0, left: 30.Fit, bottom: 0, right: 0)
        addB.addAct {
            let manager = PGDatePickManager()
            manager.cancelButtonText = "Cancel"
            manager.confirmButtonText = "Done"
            manager.confirmButtonTextColor = mainColor
            let datePicker = manager.datePicker
            datePicker?.language = "en"
            datePicker?.datePickerMode = .date
            datePicker?.middleTextColor = mainColor
            datePicker?.lineBackgroundColor = .clear
            datePicker?.delegate = self
            UIApplication.topViewController()?.present(manager, animated: true)
        }

        doneButton.left(30.Fit).right(30.Fit).height(50)
        doneButton.Top == addB.Bottom + 30.Fit
        doneButton.addAct {
            
            Toast_View_Tool.show(type:.success,text: "Success")
            let model:InfoUtil.recordDta? = InfoUtil.recordDta(type: self.typeLabel.text ?? "",desc: self.descView.text ?? "",time: self.addB.currentTitle)
            Pet_RecordManager.shared.saveRecord(model!)
            self.superview?.animatedDismiss()
            self.recordBlock?()
        }
        
        cancelButton.left(30.Fit).right(30.Fit).height(50)
        cancelButton.Top == doneButton.Bottom + 15.Fit
        cancelButton.addAct {
            self.superview?.animatedDismiss()
        }

    }
    
    func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
        let str = "\(dateComponents.year ?? 0)/\(dateComponents.month ?? 0)/\(dateComponents.day ?? 0)"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy/MM/dd"
        let date = dateFormatter.date(from: str)!
        let timeInterval:TimeInterval = date.timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        
        let now = Date()
        let dateString = dateFormatter.string(from: now) // 将 Date 对象转换为字符串
        let nowtimeInterval:TimeInterval = now.timeIntervalSince1970
        let nowtimeStamp = Int(nowtimeInterval)
        if timeStamp - nowtimeStamp > 0{
            addB.setTitle(str, for: .normal)
        }else
        {
            Toast_View_Tool.show(type: .error,text: "The selected time must be the same day or a later time")
        }
        
    }
        
    func imageToBase64String(image:UIImage)->Data?{
        let imageData = image.resetImgSize()
        return imageData
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}




class DeleteReminder_View: UIView {
    
    private var imgView = UIImageView.initImgView(img: "picture_delete content 1")
    private var tLabel = UILabel.initV(.setTypeFace(20, type: .medium), text: "Delete the Reminder?", textColor:titleColor)
    private var cLabel = UILabel.initV(.setTypeFace(14, type: .medium), text: "After it is deleted, it cannot be restored and needs to be added again.", textColor:.color(hexString: "#999999"))
    private lazy var submitBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Yes", for: .normal)
        btn.setTitleColor(mainColor, for: .normal)
        btn.titleLabel?.font = .setTypeFace(16, type: .medium)
        btn.setAllCorners(corner: 25.Fit)
        btn.backgroundColor = .black
        return btn
    }()
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Cancel", for: .normal)
        btn.setTitleColor(.color(hexString: "#999999"), for: .normal)
        btn.titleLabel?.font = .setTypeFace(16, type: .medium)
        btn.backgroundColor = .clear
        return btn
    }()
    var userID:String?
    var DoneBlock:(() -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        layer.cornerRadius = 20.Fit
        layer.maskedCorners = .allCorner
        self.subviews {
            imgView
            tLabel
            cLabel
            submitBtn
            cancelBtn
        }
        imgView.top(0).left(0).right(0).height(200.Fit)
        imgView.centerHorizontally()
        
        tLabel.textAlignment = .center
        tLabel.left(20.Fit).right(20.Fit)
        tLabel.Top == imgView.Bottom
        
        cLabel.textAlignment = .center
        cLabel.numberOfLines = 0
        cLabel.left(20.Fit).right(20.Fit).height(40.Fit)
        cLabel.Top == tLabel.Bottom + 5.Fit
        
        submitBtn.right(15.Fit).left(15.Fit).height(50.Fit)
        submitBtn.Top == cLabel.Bottom + 10.Fit
        submitBtn.addAct {
            self.superview?.animatedDismiss()
            self.DoneBlock?()
        }
        
        cancelBtn.right(15.Fit).left(15).height(50.Fit)
        cancelBtn.Top == submitBtn.Bottom
        cancelBtn.addAct {
            self.superview?.animatedDismiss()
        }

        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
